#include "admin/client/TopicManager.h"
#include "codec/RequestBuilder.h"

namespace zeroplus::mq::admin
{
    TopicManager::TopicManager()
    {
    }

    TopicManager::~TopicManager() {}

    void TopicManager::ConnectToAllBrokerServer(const routeinfo::ClusterInfo &clusterInfo)
    {
        for (const auto &entry : clusterInfo.broker_addr_table())
        {
            auto clusterName = entry.second.cluster_name();
            auto brokerName = entry.second.broker_name();
            auto brokerAddr = entry.second.broker_addrs().find(BrokerState::MASTER)->second;
            if (clientList_.find(brokerAddr) == clientList_.end())
            {
                Uri uriParser(brokerAddr);
                clientList_[brokerAddr] = std::move(std::make_unique<ClientNode>(uriParser.GetUri()));
            }
            else
            {
                LOG_DEBUG("brokerAddr has connect to brokerServer, why?");
            }
        }
    }

    bool TopicManager::AddTopic(const std::shared_ptr<ClientNode> &client, const std::string &topic)
    {
        transport::TopicCreateAndUpdateRequest request;
        request.set_topic(topic);
        RequestBuilder<transport::RequestCode::UPDATE_AND_CREATE_TOPIC,
                       transport::TopicCreateAndUpdateRequest,
                       transport::TopicCreateAndUpdateResponse>
            builder(client);
        auto [responseCode, response] = builder.InvokeSync(request);
        return true;
    }

    bool TopicManager::AddTopic(const std::vector<std::vector<std::string>> &topic2D)
    {
        assert(clientList_.size() == topic2D.size());
        int index = 0;
        for (const auto &[brokerUri, client] : clientList_)
        {
            for (const auto &topic : topic2D[index++])
            {
                LOG_DEBUG("topic: %s添加到%s中", topic.c_str(), brokerUri.c_str());
                AddTopic(client, topic);
            }
        }
    }

    bool TopicManager::DelTopic(const std::string &topic)
    {
        LOG_ERROR("not impl yet");
    }

}
